#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<string.h>
using namespace std;
#define NUM 16
#define SIZE 16

char cmd_line[NUM];
char* g_argv[SIZE];//打散之后的字符串
int main()
{
  //0.不会停止的shell
  while(1)
  {
    //1.打印提示符
    cout << "hj@VM-4-17-centos shell]$ ";
    fflush(stdout);
    memset(cmd_line,sizeof cmd_line,'\0');
    //getline(cin,cmd_line);
    if(fgets(cmd_line,NUM,stdin) == NULL)
      continue;
    cmd_line[strlen(cmd_line)-1] = '\0';
    //cout << cmd_line << endl;
    //2.解析指令
    int i= 1;
    g_argv[0] = strtok(cmd_line," ");
    while(g_argv[i++] = strtok(nullptr," "));
    //创建子进程
    pid_t id = fork();
    if(id == 0)
    {
      //child
      cout << "这是子进程执行的代码" << endl;
      execvp(g_argv[0],g_argv);
      exit(1);
    }
    int status = 0;
    pid_t ret = waitpid(id, &status, 0);
    if(ret>0)
    cout << "退出码:" << WEXITSTATUS(status) << endl;
  }
  return 0;
}
